/**
 * The js file for confReserve.jsp only
 */

//Global variable
var confInfoObj=new ConfInfo();

//Page js entrance
$(function(){
	var reserveObj=confInfoObj.getReservationObjFromParent();
	confInfoObj.init();
	if(reserveObj){
		confInfoObj.setValues(reserveObj);
	}else{
		confInfoObj.setDefaults();
	}
});

function ConfInfo(){
	var self=this,layout,participantGrid;
	
	this.init=function(){
		$('.easyui-validatebox').validatebox();
		$('.easyui-validatebox[required]').after("<font color='red'> *</font>");
		self.loadGroup();
		self.initProfile();
		self.initParticipant();
		
		layout=new dhtmlXLayoutObject("id_win_container","2U");
		layout.forEachItem(function(item){
			item.hideHeader();
		});
		layout.cells("a").setWidth(200);
		layout.cells("a").fixSize(true,true);
		layout.cells("a").attachObject("id_list");
		
		layout.cells("b").attachObject("id_container_right");
		
		self.showItem("id_general");
		
		// 高亮左侧的菜单选项
	    $(".menu-item").click(function(){
	        $(".menu-item").css("font-weight","normal");
	        $(this).css("font-weight","bold");
	    });
		
		//---------------initialize color picker------------
		var txtColorPicker, bgColorPicker;
		txtColorPicker=new dhtmlXColorPicker("id_txt_cp",false,false,true);
		txtColorPicker.loadUserLanguage("my-lang");
		txtColorPicker.setImagePath("<c:url value='/styles/dhx2/imgs/'/>");
		txtColorPicker.init();
		txtColorPicker.setOnSelectHandler(function(c){
			$("#id_textColor").val(c);
			$("#id_textColor").css("background-color",c);
		});
		$("#id_textColor").click(function(){
			txtColorPicker.show();
		});
		
		bgColorPicker=new dhtmlXColorPicker("id_bg_cp",false,false,true);
		bgColorPicker.loadUserLanguage("my-lang");
		bgColorPicker.setImagePath("<c:url value='/styles/dhx2/imgs/'/>");
		bgColorPicker.init();
		bgColorPicker.setOnSelectHandler(function(c){
			$("#id_textBgColor").val(c);
			$("#id_textBgColor").css("background-color",c);
		});
		$("#id_textBgColor").click(function(){
			bgColorPicker.show();
		});
	};
	
	this.showItem=function(id){
		var items=["id_general","id_auv","id_osd","id_broadcast","id_participant"];
		$.each(items,function(){
			if(this==id){
				document.getElementById(this).style.display="block";
			}else{
				document.getElementById(this).style.display="none";
			}
		});
	};

	this.loadGroup=function(){
		$.ajax({
			url:"<c:url value='/app/manage/group/combox'/>",
			type:"GET",
			//async:false,
			data:{
				times:new Date().valueOf()
			},
			success:function(data){
				var groups=eval(data);
				$.each(groups,function(){
					$("#id_group").append("<option value='"+this.name+"'>"+this.name+"</option>");
				});
			}
		});
	};
	
	//initialize "id_profile" select options
	this.initProfile=function(){
		$.ajax({
			url:"<c:url value='/app/manage/profile/combox'/>",
			type:"GET",
			//async:false,
			data:{
				times:new Date().toString()
			},
			success:function(data){
				var profiles=$.parseJSON(data);
				
				$.each(profiles,function(){
					$("#id_profile").append("<option value='"+this+"'>"+this+"</option>");
				});
				
				//Bind change event,put relative values from profile to this page when change event occurred
				$("#id_profile").change(function(){
					var profileName=this.value;
					if(profileName=="") return;
					if(!confirm(messages.getMsg('confirm.useProfile'))) return;
					
					self.changeProfile(profileName);
				});
			}
		});
	};
	//validate conference information
	this.isValidValues=function(){
		return $('.easyui-validatebox').validatebox("isValid");
	}
	//Change profile
	this.changeProfile=function(profileName){
		$.ajax({
			url:"<c:url value='/app/manage/profile/json'/>",
			type:"GET",
			async:false,
			data:{
				name:profileName,
				times:new Date().toString()
			},
			success:function(retData){
				var pObj=$.parseJSON(retData);
				//copy pObj values to relative elements
				$("input[name='name']").val(pObj['confName']);
				$("select[name='bandwidth']").val(pObj['bandwidth']);
				$("input[name='maxAudioPorts']").val(pObj['maxAudioPorts']);
				$("input[name='maxVideoPorts']").val(pObj['maxVideoPorts']);
				if(pObj['reservedAudioPorts']=="true"){
					$("input[name='reservedAudioPorts']").attr("checked",true);
				}else{
					$("input[name='reservedAudioPorts']").attr("checked",false);
				}
				if(pObj['reservedVideoPorts']=="true"){
					$("input[name='reservedVideoPorts']").attr("checked",true);
				}else{
					$("input[name='reservedVideoPorts']").attr("checked",false);
				}
				$("input[name='encrypt'][value='"+pObj['encrypt']+"']").attr("checked",true);
				$("input[name='callInType'][value='"+pObj['callInType']+"']").attr("checked",true);
				
				if(pObj['muteOnJoin']=="true"){
					$("input[name='muteOnJoin']").attr("checked",true);
				}else{
					$("input[name='muteOnJoin']").attr("checked",false);
				}
				var formats=pObj["audioFormats"].split(',');
				//clean checked
				$("input[name='audioFormats']").attr("checked",false);
				$.each(formats,function(){
					$("input[name='audioFormats'][value='"+this+"']").attr("checked",true);
				});
				if(pObj['h263cif4Enabled']=="true"){
					$("input[name=h263cif4Enabled]").attr("checked",true);
				}else{
					$("input[name=h263cif4Enabled]").attr("checked",false);
				}
				$("select[name=h264Definition]").val(pObj['h264Definition']);
				$("select[name=h239Bandwidth]").val(pObj['h239Bandwidth']);
				if(pObj['h239Enabled']=='true'){
					$("input[name=h239Enabled]").attr("checked",true);
				}else{
					$("input[name=h239Enabled]").attr("checked",false);
				}
				$("select[name=h239Codec]").val(pObj['h239Codec']);
				$("select[name=textPosition]").val(pObj['textPosition']);
				$("select[name=textFont]").val(pObj['textFont']);
				$("input[name=textColor]").val(pObj['textColor']);
				if(pObj['textBgEnabled']=='true'){
					$("input[name=textBgEnabled]").attr("checked",true);
				}else{
					$("input[name=textBgEnabled]").attr("checked",false);
				}
				$('input[name=textBgColor]').val(pObj['textBgColor']);
                $('input[name=textDisplayTime]').val(pObj['textDisplayTime']);
				if(pObj['broadcastEnabled']=='true'){
					$("input[name=broadcastEnabled]").attr("checked",true);
				}else{
					$("input[name=broadcastEnabled]").attr("checked",false);
				}
				$('select[name=broadcastBandwidth]').val(pObj['broadcastBandwidth']);
				$('input[name=broadcastNumLimit]').val(pObj['broadcastNumLimit']);
				$('input[name=broadcastPassword]').val(pObj['broadcastPassword']);
				$('textarea[name=topic]').val(pObj['description']);
			}
		});
	};
	
	//initialize participant tab panel
	this.initParticipant=function(){
		var toolbar=new dhtmlXToolbarObject("id_participant_bar");
		toolbar.addButton("id_participant_btn_addressbook",1,"<fmt:message key='toolbar.conf.participant.addressbook'/>","<c:url value='/styles/default/images/addressbook16.png'/>");
		toolbar.addButton("id_participant_btn_delete",2,"<fmt:message key='toolbar.conf.participant.delete'/>","<c:url value='/styles/default/images/delete16.png'/>");
		toolbar.addButtonTwoState("id_btn_email_notify", 3, "<fmt:message key='toolbar.conf.participant.email.notify'/>","<c:url value='/styles/default/images/chk_no.gif'/>");
		
		toolbar.attachEvent("onClick",function(id){
			if(id=="id_participant_btn_addressbook"){
				var popwin=layout.dhxWins.createWindow("id_win_addressbook",0,0,600,320);
				popwin.denyResize();
				popwin.setModal(true);
				popwin.center();
				popwin.button("minmax1").hide();
				popwin.button("minmax2").hide();
				popwin.setText("<fmt:message key='panel.title.addressBook'/>");
				popwin.attachURL("<c:url value='/app/manage/addressbook/win'/>?parent=reserve");
			}
			if(id=="id_participant_btn_delete"){
				var rowIds=participantGrid.getSelectedRowId();
				if(rowIds==null){
					alert(messages.getMsg("noSelect.tip"));
				}else{
					$.each(rowIds.split(","),function(){
						participantGrid.deleteRow(this);
					});
				}
			}
		});
		
		toolbar.attachEvent("onStateChange",function(id,state){
			if(id=="id_btn_email_notify"){
				if(state){
					toolbar.setItemImage("id_btn_email_notify", "<c:url value='/styles/default/images/chk_yes.gif'/>");
					$("input[name='emailNotify']").val("true");
				}else{
					toolbar.setItemImage("id_btn_email_notify", "<c:url value='/styles/default/images/chk_no.gif'/>");
					$("input[name='emailNotify']").val("false");
				}
			}
		});
		
		participantGrid=new dhtmlXGridObject("id_participant_grid");
		participantGrid.setImagePath("<c:url value='/styles/dhx2/imgs/'/>");
		participantGrid.setHeader([
		   						"<fmt:message key='grid.conf.participant.number'/>",
		   						"<fmt:message key='grid.conf.participant.displayName'/>",
		   						"<fmt:message key='grid.conf.participant.invite'/>",
		   						"<fmt:message key='grid.conf.participant.IP'/>",
		   						"<fmt:message key='grid.conf.participant.video'/>",
		   						"<fmt:message key='grid.conf.participant.bandwidth'/>",
		   						"email",
		   						"name"
		   		                ],null,[
		   		                        "text-align:center",
		   		                        "text-align:center",
		   		                        "text-align:center",
		   		                        "text-align:center",
		   		                        "text-align:center",
		   		                        "text-align:center",
		   		                     	"text-align:center",
		   		                     	"text-align:center"
		   		                     ]);
		participantGrid.setInitWidths("80,80,80,60,40,80,0,0");
	   	participantGrid.setColTypes("ro,ed,ch,ro,ch,coro,ro,ro");
	   	participantGrid.setColumnColor("white,yellow,white,white,white,yellow,white,white");
	   	participantGrid.enableMultiselect(true);
	   	var combo=participantGrid.getCombo(5);
	   	$.each([128,192,256,320,384,448,512,640,768,1024,1536,1920,2048,2560,3072,3584,4096],function(){
	   		combo.put(this,this);
	   	});
	   	participantGrid.setSkin("${skin}");
	   	participantGrid.init();
	};
	//Get conference information as a json string
	this.getConfValues=function(){
		var ret={};
		
		$("#id_container_right").find("input,select,textarea").each(function(){
			var $tg=$(this),t = this.type, tag = this.tagName.toLowerCase(),name=this.name;
			
			if(name&&typeof(ret[name])=="undefined"){
				if (t == 'hidden' || t == 'text' || t == 'password' || tag == 'textarea' || tag == 'select'){
					ret[name]=$tg.val();
				}else if (t == 'checkbox'){
					var $e=$("input[name='"+name+"']"),values="";
					
					if($e.length==1){
						values=$e.attr("checked")?"true":"false";
					}else if($e.length>1){
						values="";
						var $chks=$e.filter(":checked");
						$chks.each(function(i){
							//values.push(this.value);
							values+=this.value;
							if(i!=$chks.length-1)
								values+=",";
						});
					}
					ret[name]=values;
				}else if(t == 'radio'){
					ret[name]=$("input[name='"+name+"']").filter(":checked").val()||"";
				}
			}
		});
		
		ret["participants"]=self.getPTCs();
		return $.toJSON(ret);
	};
	
	//Get participants from grid
	this.getPTCs=function(){
		var participants=[];
		participantGrid.forEachRow(function(id){
			var p={
				p_number:participantGrid.cells(id,0).getValue(),
				p_nameOverrideValue:participantGrid.cells(id,1).getValue(),
				p_autoInvite:participantGrid.cells(id,2).getValue()=="1"?"true":"false",
				p_ip:participantGrid.cells(id,3).getValue(),
				p_videoEnabled:participantGrid.cells(id,4).getValue()=="1"?"true":"false",
				p_bandwidth:participantGrid.cells(id,5).getValue(),
				p_email:participantGrid.cells(id,6).getValue(),
				p_name:participantGrid.cells(id,7).getValue()
			};
			participants.push(p);
		});
		
		//alert($.toJSON(participants));
		return participants;
	};
	
	//Set participants into grid
	this.setPTCs=function(ptcArray){
		if(ptcArray){
			$.each(ptcArray,function(){
				var rowId=this.p_number;
				var row=[
							this.p_number,
							this.p_nameOverrideValue,
							this.p_autoInvite=="true"?"1":"0",
				         	this.p_ip,
				         	this.p_videoEnabled=="true"?"1":"0",
				         	this.p_bandwidth
				           ];
				participantGrid.addRow(rowId,row);
			});
		}
	};
	
	//Set conference information
	this.setValues=function(reserveObj){
		if(reserveObj){
			$.each(reserveObj,function(k,v){
				var $tg=$("#id_container_right").find("*[name='"+k+"']"),len=$tg.length;
				if(k=="participants"){
					self.setPTCs(reserveObj["participants"]);
				}else if(len>0){
					var tag = $tg.attr("tagName").toLowerCase(),t=$tg.attr("type");
					if(t == 'hidden' || t == 'text' || t == 'password' || tag == 'textarea' || tag == 'select'){
						$tg.val(v);
						//if(k=="number"){
						//	$tg.attr("readonly",true).css({"background-color":"#DEDBD6"});
						//}
					}else if(t == 'checkbox'){
						if(len==1){
							$tg.attr("checked",v=="true");
						}else{
							var _v=v||[];
							if(_v.constructor==String){
								_v=_v.split(",");
							}
							$.each(_v,function(){
								$tg.filter("*[value='"+this+"']").attr("checked",true);
							});
						}
					}else if(t == 'radio'){
						$tg.filter("*[value='"+v+"']").attr("checked",true);
					}
				}
			});
		}
	};
	
	//Get reservation information from parent page
	this.getReservationObjFromParent=function(){
		return parent.confReserveViewObj.getReservationObj();
	};
	//Set default conference information
	this.setDefaults=function(){
		$("select[name=bandwidth]").val("1024");
		$("input[name=callInType][value=all]").attr("checked",true);
		$("input[name=encrypt][value=disable]").attr("checked",true);
		$("input[name=h263cif4Enabled]").attr("checked",true);
		$("input[name=h264Enabled]").attr("checked",true);
		$("select[name=h264Definition]").val("HD720P");
		$("input[name=h239Enabled]").attr("checked",true);
		$("select[name=h239Bandwidth]").val("128");
		$("select[name=h239Codec]").val("H.263");
		
		$("input[name=audioFormats]").each(function(){
			this.checked=true;
		});
		
		$("select[name=textPosition]").val("bottom_center");
		$("select[name=textFont]").val("middle");
		
		$("select[name=broadcastBandwidth]").val("384");
	};
	//Get value for representing recurring event text
	this.getText=function(){
		return $("input[name='name']").val();
	};
	
	this.closeWin=function(){
		if(layout.dhxWins.isWindow("id_win_addressbook")){
			layout.dhxWins.window("id_win_addressbook").close();
		}
	};
	
	this.getPTCGrid=function(){
		return participantGrid;
	};
	
	this.getConfNumber=function(){
		return $("input[name='number']").val();
	};
	
	this.getConfTopic=function(){
		return $("textarea[name='topic']").val();
	};
}